let config = require('./config.js');
import MD5G from './md5utf-8.js';
// 成功弹框
function successToast(title) {
	uni.showToast({
		title: title,
		mask: false,
		icon: 'success',
		duration: 2000
	})
}

function showToast(title) {
	uni.showToast({
		title: title,
		mask: false,
		icon: 'none',
		duration: 2000
	})
}
// 加载中弹框
function loadingToast(title = '加载中...') {
	uni.showLoading({
		title: title,
		mask: true,
		duration: 2000
	})
}

function hideToast() {
	uni.hideLoading();
	uni.hideToast();
}

function isEmpty(obj) {
	if (obj == "undefined" || obj == null || obj == "" || obj == undefined || JSON.stringify(obj) == "{}") {
		return true;
	} else {
		return false;
	}
}

function formatSeconds(s) {
	var t;
	if (s > -1) {
		var hour = Math.floor(s / 3600);
		var min = Math.floor(s / 60) % 60;
		var sec = s % 60;
		if (hour < 10) {
			t = '0' + hour + ":";
		} else {
			t = hour + ":";
		}

		if (min < 10) {
			t += "0";
		}
		t += min + ":";
		if (sec < 10) {
			t += "0";
		}
		t += sec.toFixed(0);
	}
	return t;
}


function trimSpace(array) {
	for (var i = 0; i < array.length; i++) {
		if (array[i] == " " || array[i] == null || typeof(array[i]) == "undefined" || array[i] == "") {
			array.splice(i, 1);
			i = i - 1;

		}
	}
	return array;
}
/**
 * 音频播放时间换算
 * @param {number} value - 音频当前播放时间，单位秒
 */
function transTime(value) {
	var time = "";
	var h = parseInt(value / 3600);
	value %= 3600;
	var m = parseInt(value / 60);
	var s = parseInt(value % 60);
	if (h > 0) {
		time = formatTime(h + ":" + m + ":" + s);
	} else {
		time = formatTime(m + ":" + s);
	}
	return time;
}
/**
 * 格式化时间显示，补零对齐
 * eg：2:4  -->  02:04
 * @param {string} value - 形如 h:m:s 的字符串
 */
function formatTime(value) {
	var time = "";
	var s = value.split(":");
	var i = 0;
	for (; i < s.length - 1; i++) {
		time += s[i].length == 1 ? "0" + s[i] : s[i];
		time += ":";
	}
	time += s[i].length == 1 ? "0" + s[i] : s[i];
	return time;
}
//格式化时间
function formatDateTime(time) {
	var dd = parseInt(time / 1000 / 60 / 60 / 24, 10);
	var hh = parseInt((time / 1000 / 60 / 60) % 24, 10);
	var mm = parseInt((time / 1000 / 60) % 60, 10);
	var ss = parseInt((time / 1000) % 60, 10);
	dd = dd < 10 ? "0" + dd : dd; //天
	hh = hh < 10 ? "0" + hh : hh; //时
	mm = mm < 10 ? "0" + mm : mm; //分
	ss = ss < 10 ? "0" + ss : ss; //秒
	return mm + ":" + ss;
}

// 判断登录状态
function checkSession(url = getCurrentPageUrlWithArgs()) {
	if (uni.getStorageSync('authToken')) {

	} else {
		if (url != "pages/login/login") {
			uni.setStorageSync('backurl', url)
			uni.redirectTo({
				url: "/pages/login/login?backurl=" + encodeURIComponent(url)
			})
		}
	}
}
// 获取当前页面路径
function getCurrentPageUrlWithArgs() {
	var pages = getCurrentPages(); //获取加载的页面
	if (pages == '') {
		return 'pages/login/login'
	}
	var currentPage = pages[pages.length - 1] //获取当前页面的对象
	var url = currentPage.route //当前页面url
	var options = currentPage.options //如果要获取url中所带的参数可以查看options
	//拼接url的参数
	var urlWithArgs = url + '?'
	for (var key in options) {
		var value = options[key]
		urlWithArgs += key + '=' + value + '&'
	}
	urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
	return urlWithArgs
}
// 判断是否存在http 或https
function ishttp(str) {
	var arr = ['https', 'http'];
	str = str.substring(0, 4);
	if (arr.indexOf(str) == -1) {
		return false;
	} else {
		return true;
	}
}

/**
 * 存储localStorage
 */
function setLocalStorage(key, data) {
	if (typeof data == "string") {
		uni.setStorageSync(key, data);
		return;
	}
	try {
		uni.setStorageSync(key, JSON.stringify(data));
	} catch (e) {}
}
/**
 * 获取localStorage
 */
function getLocalStorage(key) {
	let values = uni.getStorageSync(key);
	if (values === undefined) {
		return "";
	}
	try {
		return JSON.parse(values, null);
	} catch (e) {
		return values;
	}
}

/**
 * 删除localStorage
 */
function removeLocalStorage(name) {
	if (!name) return;
	uni.removeStorage({
		key: name,
		success: (result) => {

		},
		fail: () => {},
		complete: () => {}
	});
}

function idCard(val) {
	return /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/.test(val)
}

function mobile(val) {
	return /^1[0-9]{10}$/.test(val)
}

function islogin() {
	uni.showModal({
		title: '您还未登录',
		content: '请登录再进行操作',
		showCancel: true,
		cancelText: '暂不登录',
		cancelColor: '#000000',
		confirmText: '立即登录',
		confirmColor: '#3CC51F',
		success: res => {
			if (res.confirm == true) {
				removeLocalStorage('user');
				removeLocalStorage('assistmode');
				removeLocalStorage('authToken');
				removeLocalStorage('supplier');
				removeLocalStorage('serverTime');
				removeLocalStorage('config');
				checkSession();
			}
		}
	});
}
/* 数组取几个 */
function getRandomArrayElements(arr, count) {
	var shuffled = arr.slice(0),
		i = arr.length,
		min = i - count,
		temp, index;
	while (i-- > min) {
		index = Math.floor((i + 1) * Math.random());
		temp = shuffled[index];
		shuffled[index] = shuffled[i];
		shuffled[i] = temp;
	}
	return shuffled.slice(min);
}
//api签名
function getSign(params) {
	var str = '';
	var sortparams = objKeySort(params);
	for (var p in sortparams) {
		if (params[p] != '') {
			str += p + '=' + params[p] + '&';
		}
	}
	str = str + config.ACCESS;
	console.info('匹配后台签名校验:',str);
	str = MD5G.md5(str);
	console.info(str)
	return str.toLowerCase();
}
//排序的函数
function objKeySort(arys) { 
    var newkey = Object.keys(arys).sort();
    var newObj = {}; 
    for (var i = 0; i < newkey.length; i++) {
    newObj[newkey[i]] = arys[newkey[i]];
    }
    return newObj; //返回排好序的新对象
}
function Urlencode(str) {
	str = (str + '').toString();
	return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
	replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

function GetUrlKey(name) {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(
		/\+/g, '%20')) || null
}
function clickCallPhone(phone) {
	if (isExist(phone) && phone.length >= 8) {
		var content = '是否拨打电话：' + phone;
		uni.showModal({
			title: '提示',
			content: content,
			success: function(res) {
				if (res.confirm) {
					uni.makePhoneCall({
						phoneNumber: phone //仅为示例
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	} else {
		uni.showToast({
			title: '未有联系方式',
			duration: 1000,
			icon: 'none'
		});
		setTimeout(function() {
			uni.hideToast();
		}, 1000);
	}
}
function isIphoneX() {
	// 判断是iphoneX及以后的iphone手机（即iphone带全面屏的手机）
	if (window && navigator.userAgent.indexOf('iPhone') > -1 && window.screen.height >= 812) {
		return true;
	} else {
		return false;
	}

}
/**
 * 判断是否为微信客户端
 */
function isWinXin() {
	var isWeiXin = navigator.userAgent.toLowerCase().indexOf('micromessenger') > -1 ? true : false;
	return isWeiXin;
}
/**
 * 是否存在字符
 * @param {Object} value
 */
function isExist(value) {
	if (value !== null && value !== undefined && value !== "undefined" && value !== "null" && value.length > 0) {
		return true;
	} else {
		return false;
	}
}

export default {
	getSign,
	Urlencode,
	GetUrlKey,
	successToast,
	showToast,
	loadingToast,
	hideToast,
	isEmpty,
	ishttp,
	formatSeconds,
	trimSpace,
	transTime,
	formatDateTime,
	checkSession,
	setLocalStorage,
	getLocalStorage,
	removeLocalStorage,
	islogin,
	idCard,
	mobile,
	getRandomArrayElements,
	clickCallPhone,
	isIphoneX,
	isWinXin,
	isExist
}
